package org.jeecgframework.web.cgform.controller.button;

import com.tongan.entity.button.CButtonFunctionTypeEnum;
import com.tongan.entity.button.CgformButtonEntity;
import com.tongan.entity.button.CgformButtonFieldConfig;
import com.tongan.entity.config.CgFormFieldEntity;
import com.tongan.entity.config.CgFormHeadEntity;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.cgform.service.button.CgformButtonServiceI;
import org.jeecgframework.web.cgform.service.config.CgFormFieldServiceI;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**   
 * @Title: Controller
 * @Description: 表单自定义按钮
 * @author 张代浩
 * @date 2013-08-07 20:16:26
 * @version V1.0   
 *
 */
//@Scope("prototype")
@Controller
@RequestMapping("/cgformButtonController")
public class CgformButtonController extends BaseController {
	/**
	 * Logger for this class
	 */
	@SuppressWarnings("unused")
	private static final Logger logger = Logger.getLogger(CgformButtonController.class);

	@Autowired
	private CgformButtonServiceI cgformButtonService;
	@Autowired
	private SystemService systemService;


	/**
	 * 表单自定义按钮列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "cgformButton")
	public ModelAndView cgformButton(HttpServletRequest request) {
		String formId = request.getParameter("formId");
		String tableName = request.getParameter("tableName");
		request.setAttribute("formId", formId);
		request.setAttribute("tableName", tableName);
		return new ModelAndView("jeecg/cgform/button/cgformButtonList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@SuppressWarnings("unchecked")
	@RequestMapping(params = "datagrid")
	public void datagrid(CgformButtonEntity cgformButton,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(CgformButtonEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cgformButton, request.getParameterMap());
		this.cgformButtonService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除表单自定义按钮
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(CgformButtonEntity cgformButton, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		cgformButton = systemService.getEntity(CgformButtonEntity.class, cgformButton.getId());
		message = "删除成功";
		cgformButtonService.delete(cgformButton);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加表单自定义按钮
	 *
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(CgformButtonEntity cgformButton, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
//		if("add".equalsIgnoreCase(cgformButton.getButtonCode())
//				||"update".equalsIgnoreCase(cgformButton.getButtonCode())
//				||"delete".equalsIgnoreCase(cgformButton.getButtonCode())){
//			message = "按钮编码不能是add/update/delete";
//			j.setMsg(message);
//			return j;
//		}
		List<CgformButtonEntity> list =  cgformButtonService.checkCgformButton(cgformButton);
		if(list!=null&&list.size()>0){
			message = "按钮编码已经存在";
			j.setMsg(message);
			return j;
		}
		if (cgformButton.getFunctionType()!= CButtonFunctionTypeEnum.ManyToManyType){
			cgformButton.setManytomanytable(null);
		}
		if (StringUtil.isNotEmpty(cgformButton.getId())) {
			message = "更新成功";
			CgformButtonEntity t = cgformButtonService.get(CgformButtonEntity.class, cgformButton.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(cgformButton, t);
				cgformButtonService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			message = "添加成功";
			cgformButtonService.save(cgformButton);
			//基本类型时
            //设置默认按钮
            cgformButton.setFieldConfigs(getDefaultFieldConfigs(cgformButton.getId(),cgformButton.getFormId()));
            cgformButtonService.updateFieldConfig(cgformButton);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	@Resource
	CgFormFieldServiceI cgFormFieldServiceI;

	/**
	 * 表单自定义按钮列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(CgformButtonEntity cgformButton, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cgformButton.getId())) {
			cgformButton = cgformButtonService.getEntity(CgformButtonEntity.class, cgformButton.getId());
		}

		String sql="SELECT *\n" +
				"FROM cgform_head WHERE id IN (\n" +
				"SELECT DISTINCT (table_id)\n" +
				"FROM cgform_field f WHERE foreignTableId='"+cgformButton.getFormId()+"')\n" +
				"AND jform_type=4";
		List<CgFormHeadEntity> heads=cgFormFieldServiceI.findListbySql(sql,CgFormHeadEntity.class);
		req.setAttribute("heads",heads);
		req.setAttribute("cgformButtonPage", cgformButton);
		return new ModelAndView("jeecg/cgform/button/cgformButton");
	}

	/**
	 * 获取默认的字段配置
	 * 不能为空会选中
	 * @param buttonId
	 * @param formId
	 * @return
	 */
	public List<CgformButtonFieldConfig> getDefaultFieldConfigs(String buttonId,String formId){
		Map<String,CgFormFieldEntity> fieldEntityMap=cgFormFieldServiceI.getCgFormFieldByFormId(formId);

		List<CgformButtonFieldConfig> configs=cgformButtonService.getFieldConfigs(buttonId);
		if (configs==null || configs.size()==0){
			fieldEntityMap.values().forEach(field->{
				CgformButtonFieldConfig config=new CgformButtonFieldConfig();
				config.setButtonId(buttonId);
				config.setFieldId(field.getId());
				config.setEditable("N".equals(field.getIsNull()));
				configs.add(config);
			});
		}
		return configs;
	}

	/**
	 * 获取字段列表
	 * @param buttonId
	 * @param formId
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "fieldList")
	public ModelAndView fieldList(String buttonId,String formId,HttpServletRequest req){
		req.setAttribute("buttonId",buttonId);
		req.setAttribute("formId",formId);
		req.setAttribute("fieldEntityMap",cgFormFieldServiceI.getCgFormFieldByFormId(formId).values());
		req.setAttribute("configs",getDefaultFieldConfigs(buttonId,formId).stream().collect(Collectors.toMap(
				s->s.getFieldId(),
				s->s
		)));
		return new ModelAndView("jeecg/cgform/button/cgformFieldConfig");
	}

	@RequestMapping(params = "saveFieldList")
	@ResponseBody
	public Object saveFieldList(CgformButtonEntity cgformButton,HttpServletRequest req){
		String message = null;
		AjaxJson j = new AjaxJson();
		if (org.apache.commons.lang3.StringUtils.isNotBlank(cgformButton.getId())){
			cgformButtonService.updateFieldConfig(cgformButton);
		}
		return j;
	}
}
